import paho.mqtt.client as mqtt
import time

# MQTT服务器配置
MQTT_BROKER = "mqtt.eclipseprojects.io"  # 公共MQTT服务器
MQTT_PORT = 1883  # 非加密端口
MQTT_KEEPALIVE = 60  # 心跳间隔(秒)
MQTT_TOPIC = "python/mqtt/example"  # 要订阅/发布的主题


# 连接回调函数
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("成功连接到MQTT服务器")
        # 连接成功后订阅主题
        client.subscribe(MQTT_TOPIC)
        print(f"已订阅主题: {MQTT_TOPIC}")
    else:
        print(f"连接失败，错误代码: {rc}")


# 消息接收回调函数
def on_message(client, userdata, msg):
    print(f"\n收到消息 - 主题: {msg.topic} 内容: {msg.payload.decode()}")


# 发布消息回调函数
def on_publish(client, userdata, mid):
    print(f"消息发布成功，消息ID: {mid}")


def main():
    # 创建MQTT客户端实例
    client = mqtt.Client()

    # 设置回调函数
    client.on_connect = on_connect
    client.on_message = on_message
    client.on_publish = on_publish

    # 连接到MQTT服务器
    print(f"连接到MQTT服务器: {MQTT_BROKER}:{MQTT_PORT}")
    client.connect(MQTT_BROKER, MQTT_PORT, MQTT_KEEPALIVE)

    # 启动网络循环(非阻塞方式)
    client.loop_start()

    try:
        # 发布几条测试消息
        for i in range(3):
            message = f"这是第 {i + 1} 条测试消息"
            print(f"\n发布消息到主题 {MQTT_TOPIC}: {message}")
            client.publish(MQTT_TOPIC, message)
            time.sleep(2)

        # 保持连接一段时间以接收可能的消息
        print("\n保持连接中，等待接收消息(10秒)...")
        time.sleep(10)

    except KeyboardInterrupt:
        print("\n用户中断程序")
    finally:
        # 停止网络循环并断开连接
        client.loop_stop()
        client.disconnect()
        print("已断开与MQTT服务器的连接")


if __name__ == "__main__":
    main()
